package org.mtmi.io.controls;

import java.io.IOException;

import net.n3.nanoxml.IXMLElement;

import org.mtmi.io.ReaderError;
import org.mtmi.io.SceneReader;
import org.mtmi.io.SceneWriter;
import org.mtmi.io.XMLReader;
import org.mtmi.io.XMLWriter;
import org.mtmi.ui.controls.AbstractRangeValueControl;
import org.mtmi.ui.controls.Control;
import org.mtmi.ui.controls.listeners.ValueChangedListener;

/**
 * In addition to {@link ControlIO}, save {@link ValueControlledControlIO } features:
 * <ul>
 * <li> the value and min, max of allowed value range
 * <li> the list of control listening value changed events.
 * </ul>
 */
public class RangeValueControlIO extends ValueControlledControlIO
{
	public static final String E_VALUES="values"; //$NON-NLS-1$
	public static final String E_VALUE_CHANGED_LISTENER ="valueChangedListener"; //$NON-NLS-1$
	public static final String A_VALUE="value"; //$NON-NLS-1$
	public static final String A_MIN="min"; //$NON-NLS-1$
	public static final String A_MAX="max"; //$NON-NLS-1$
	
	@Override
	public void writeControl( Control c, XMLWriter w, SceneWriter sw ) throws IOException 
	{
		super.writeControl( c, w, sw );
		
		if( c instanceof AbstractRangeValueControl ) 
		{
			AbstractRangeValueControl avr = (AbstractRangeValueControl)c;
		
			//values
			w.addElement( E_VALUES, A_VALUE, avr.getValue(), A_MIN, avr.getMinValue(), A_MAX, avr.getMaxValue() );
			
			//listeners
			ValueChangedListener vcl[] = avr.getValueChangedListeners();
			if( vcl!=null && vcl.length>0 ) {
				for( ValueChangedListener l : vcl ) {
					if( l instanceof Control ) {
						w.addElement( E_VALUE_CHANGED_LISTENER, A_ID, sw.getControlId( (Control)l ) );
					}
				}
			}
		}
	}
	
	@Override
	public void readControl( Control c, IXMLElement element, XMLReader r, SceneReader sr ) throws ReaderError 
	{
		super.readControl(c, element, r, sr);
		
		if( c instanceof AbstractRangeValueControl ) 
		{
			AbstractRangeValueControl avr = (AbstractRangeValueControl)c;
			
			//values
			IXMLElement e = r.getElement( element, E_VALUES, true );
			int value = r.getAttrInt( e, A_VALUE );
			int min = r.getAttrInt( e, A_MIN );
			int max = r.getAttrInt( e, A_MAX );
			avr.setRange( min, max );
			avr.setValue( value );
			
			//listeners
			for( Object o : element.getChildren() ) {
				if( o instanceof IXMLElement ) {
					e = (IXMLElement)o;
					if( E_VALUE_CHANGED_LISTENER.equals( e.getName() ) ) {
						int id = r.getAttrInt( e, A_ID );
						ValueChangedListener listener = (ValueChangedListener)sr.getControl( id );
						avr.addValueChangedListener( listener );
					}
				}
			}
		}
	}
}
